package com.dmall.chapter04.section06;

import com.dmall.chapter02.section09.Graph;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 单源路径问题的小优化
 * 只用一个数组(pre)
 * @author wx
 * @date 2020-02-25 20:15:18
 */
public class SingleSourcePath {

    private Graph G;
    private int[] pre;
    private int s;

    public SingleSourcePath(Graph G, int s) {
        G.validateVertex(s);
        this.G = G;
        this.s = s;
        this.pre = new int[G.V()];
        for (int i = 0; i < pre.length; i++) {
            pre[i] = -1;
        }
        dfs(s, s);
    }

    private void dfs(int v, int parent) {
        pre[v] = parent;
        for (int w : G.adj(v)) {
            if (pre[w] == -1) {
                dfs(w, v);
            }
        }
    }

    public boolean isConnectedTo(int t) {
        G.validateVertex(t);
        return pre[t] != -1;
    }

    public Iterable<Integer> path(int t) {
        List<Integer> res = new ArrayList<>();
        if (!isConnectedTo(t)) {
            return res;
        }
        int cur = t;

        while (cur != s) {
            res.add(cur);
            cur = pre[cur];
        }
        res.add(s);
        Collections.reverse(res);
        return res;
    }

    public static void main(String[] args) {
        String filename = SingleSourcePath.class.getClassLoader().getResource("g.txt").getPath();
        Graph g = new Graph(filename);
        SingleSourcePath singleSourcePath = new SingleSourcePath(g, 0);
        System.out.println("0 -> 6 : " + singleSourcePath.path(6));
        System.out.println("0 -> 5 : " + singleSourcePath.path(5));
    }
}
